const app = getApp()
const imgBaseUrl=app.globalData.imgBaseUrl;
const imgPreUrl=app.globalData.imgPreUrl;
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk,interval;;
Page({
  data: {
    imgBaseUrl: imgBaseUrl,
    imgPreUrl:imgPreUrl,
    scrollLeft:0,
    redHidden:true,
    pullRefresh:false,
    pro:{},
    imgUrls:[],
    indicatorDots: true,
    circular: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    addClick:true,
    regionList:[
      {
        id:1,
        name:'运河区'
      },{
        id:2,
        name:'新华区'
      },{
        id: 3,
        name: '高新区'
      }, {
        id: 4,
        name: '开发区'
      }
    ],
    regionName:"运...",
    regionIndex:0,
    tabs: [],
    activeIndex:0,
    banner:imgBaseUrl+"/banner1.png",
    goodsList:[],
    userLocation: true,
    inArea:true,
    cartNum:0,
    req1:false,
    marqueePace: 0.5,
    marqueeDistance: 0,
    marquee_margin: 30,
    smallLength: 0,
    interval1: 20,
    size:18
  },
  onLoad: function () {
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'KWSBZ-KQ5EW-6EKRD-OVGJF-6D27E-CHBHX'
    });   
    var that=this;
    that.reqData1();
  },
  reqData1:function(){
    var that=this;
    app.func.postReq('/text/index.php/home/product/plists', {}, function (res) {
      console.log(res);
      if (res.category) {
        var nodata = {};
        for (let i = 0, len = res.category.length; i < len; i++) {
          var page = 'page' + res.category[i].id;
          nodata['nodata' + res.category[i].id] = false;
          that.setData({
            [`page${res.category[i].id}`]: 2,
            [`readMore${res.category[i].id}`]: true,
          })
        }
        that.setData({
          nodata: nodata
        })
      }
      if(res.user){
        that.setData({
          user:res.user
        })
        if (res.user.newp==1){
          var redHidden=true;
        }else{
          var redHidden = false;
        }
      }else{
        var redHidden = false;
      }
      var warning = [];
      var str = res.web.warning;
      console.log(str.length);
      var len = str.length/42;
      for (var i = 0; i < len; i++) {
        var str1 = str.substring(i*42,(i+1)*42);
        warning.push(str1);
      }
      that.setData({
        category: res.category,
        activeId: that.data.activeId ? that.data.activeId:res.category[0].id,
        pro: res.pro ? res.pro : {},
        req1:true,
        newprice:parseFloat(res.web.newprice),
        redHidden: redHidden,
        warning:warning
      })
      that.setData({ goodsList: res.product})
      // that.scrolltxt();
      var timer1=setTimeout(function(){
        clearTimeout(timer1);
        wx.stopPullDownRefresh();
        that.setData({
          pullRefresh:false
        })
      },1000)
    })
  },
  reqData2: function () {
    var that = this;
    var activeId=that.data.activeId;
    var page = that.data[`page${activeId}`];
    var goodsList=that.data.goodsList[activeId];
    app.func.postReq('/text/index.php/home/product/promore', { p: page, category: activeId}, function (res) {
      var readMore, nodata;
      if (res.product) {
        readMore = res.product.length < 20 ? false : true;
        goodsList = goodsList.concat(res.product);
        nodata = goodsList.length > 4 &&res.product.length < 20 ? true : false;
      } else {
        readMore = false;
        nodata = true;
      }
      that.setData({
        [`goodsList.${activeId}`]: goodsList,
        [`page${that.data.activeId}`]: ++page,
        [`nodata.nodata${that.data.activeId}`]: nodata,
        [`readMore${that.data.activeId}`]: readMore,
        loadHidden: false
      })
    })
  },
  isLocation(){
    if(wx.getStorageSync('location')){
      return true;
    }
  },
  onShow:function(res){
    this.setData({
      isLogin: app.isLogin()
    })
    var that=this; 
    if(!that.data.latitude||!that.data.userLocation){
      that.getLocation();
    }
    if(that.data.isLogin){
      that.getCartNum();
    }
    if(that.data.req1){
      that.getEveryCar();
    }
  },
  getEveryCar:function(getCartNum,e,getmoney){
    var that=this;
    app.func.postReq('/text/index.php/home/shopcar/everycar', {}, function (res) {
      that.setData({
        pro: res.pro
      })
      if (getCartNum==1){
        that.getCartNum(1,e,getmoney);
      }
    })
  },
  getCartNum:function(addcart,e,getmoney){
    var that=this;
    app.func.postReq('/text/index.php/home/shopcar/cars', {}, function (res) {
      if (parseFloat(res) > 0) {
        wx.setTabBarBadge({
          index: 2,
          text: res.toString(),
        }) 
      }
      that.setData({
        cartNum: res
      })
      console.log(getmoney);
      if (addcart&&!getmoney) {
        that.addCart(e)
      }
    })
  },
  getLocation(){
    var that=this;
    wx.getLocation({
      success: function (res) {
        console.log(res);
        if (res.errMsg == "getLocation:ok") {
          that.setData({
            userLocation: true,
            latitude: res.latitude,
            longitude: res.longitude
          })
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success: function (res) {
              if (res.status == 0) {
                var lcity = res.result.address_component.city;
                var larea = res.result.address_component.district;
                var inArea;
                console.log(lcity,larea);
                if (lcity.indexOf("沧州") != -1) {
                  //如果在沧州
                  // if (larea.indexOf("运河") != -1 || larea.indexOf("新华") != -1) {
                  //   inArea = true;
                  // } else {
                  //   inArea = false;
                  // }
                  if (larea.indexOf("沧县") == -1 
                  && larea.indexOf("青县") == -1 
                  && larea.indexOf("东光") == -1 
                  && larea.indexOf("海兴") == -1 
                  && larea.indexOf("盐山") == -1 
                  && larea.indexOf("肃宁") == -1 
                  && larea.indexOf("南皮") == -1 
                  && larea.indexOf("吴桥") == -1 
                  && larea.indexOf("献县") == -1 
                  && larea.indexOf("孟村") == -1 
                  && larea.indexOf("泊头") == -1 
                  && larea.indexOf("任丘") == -1 
                  && larea.indexOf("黄骅") == -1 
                  && larea.indexOf("河间") == -1 
                  && larea.indexOf("渤海")==-1){
                    inArea=true;
                  }else{
                    inArea=false;
                    // 测试修改
                    // inArea=true;
                  }

                } else {
                  inArea = false;
                }
                that.setData({
                  inArea: inArea,
                  regionName: larea.substring(0, 1) + "..."
                })
              }
            },
            fail: function (res) {
              console.log('逆地址解析失败', res);
            }
          });
        }
      },
      fail: function (res) {
        console.log('获取经纬度失败', res);
        if (res.errMsg == "getLocation:fail auth deny") {
          that.setData({
            userLocation: false
          })
        }
      }
    })
  },
  prevent:function(){
    //阻止冒泡
  },
  getUserInfo: function (e) {
    var that = this;
    var data = {};
    if (e.detail.errMsg == "getUserInfo:ok") {
      that.login(e.detail.userInfo, e);
    }
  },
  bindGoodsDetail(e){
    var id=e.currentTarget.dataset.id;
    if(id!=0){
      wx.navigateTo({
        url: '../goodsdetail/goodsdetail?id='+id,
      })
    }
  },
  login: function (data,e,getmoney) {
    var that = this;
    wx.login({
      success: res => {
        data.code = res.code;
        console.log(data);
        app.func.postReq('/text/index.php/home/login/adduser', data, function (res) {
          if(res){
            that.setData({
              user:res.users
            })
            wx.setStorageSync('hhh', res.users.id)
            that.setData({isLogin:1})
            that.getEveryCar(1,e,getmoney);
            if(getmoney){
              that.getNewMoney();
            }
          }
        })
      }
    })
  },
  bindRegionChange:function(e){
    var index = e.detail.value;
    var regionList = this.data.regionList;
    var name = regionList[index].name;
    var showName=name.substring(0,1)+"...";
    // if (!this.data.inArea) {
    //   this.reqData1();
    // }
    this.setData({
      regionIndex:index,
      regionName: showName,
      inArea: true
    })
  },
  tabClick: function (e) {
    var {index,id} = e.currentTarget.dataset;
    console.group('tabClick');
      console.log(e.currentTarget.dataset);
    console.groupEnd();

    this.setData({
      activeId:id,
      activeIndex:index
    }) 
    wx.pageScrollTo({
      scrollTop: 0,
      duration:0
    })
  },
  addCart:function(e){
    const that=this;
    // var addClick=that.data.addClick;
    // if(!addClick){
    //   return;
    // }
    // that.setData({
    //   addClick:false
    // })
    // var timern=setTimeout(function(){
    //   clearTimeout(timern);
    //   that.setData({
    //     addClick:true
    //   })
    // },500);
    var id=e.currentTarget.dataset.id;
    // var {id,num,cartnum}=e.currentTarget.dataset;
    // console.log(num,cartnum);
    // if(parseFloat(cartnum)>=parseFloat(num)){
    //   wx.showToast({
    //     title: '库存不足!',
    //     icon:'none'
    //   })
    //   return;
    // }
    var pro=that.data.pro;
    var cartNum=that.data.cartNum;
    cartNum+=1;
    if (pro&&pro[id]){
      pro[id] = parseInt(pro[id])+1;
    }else{
      pro=pro==null?{}:pro;
      pro[id]=1;
    }
    wx.setTabBarBadge({
      index: 2,
      text: cartNum.toString(),
    })
    that.setData({
      pro:pro,
      cartNum: cartNum
    })
    app.func.postReq('/text/index.php/home/shopcar/addscar',{pid:id,num:1},function(res){
      
    })
  }, 
  jianCart: function (e) {
    const that = this;
    var id = e.currentTarget.dataset.id;
    var pro = that.data.pro;
    var cartNum = that.data.cartNum;
    cartNum -= 1;
    if (parseInt(pro[id])==0){
      return;
    }
    pro[id] = parseInt(pro[id]) - 1;
    that.setData({
      pro: pro,
      cartNum: cartNum
    })
    if(cartNum>0){
      wx.setTabBarBadge({
        index: 2,
        text: cartNum.toString(),
      })
    }else{
      wx.removeTabBarBadge({
        index:2
      })
    }
    app.func.postReq('/text/index.php/home/shopcar/minuescar',{pid:id,num:1},function(res){

    })
  },
  onReachBottom:function(){
    if (this.data[`readMore${this.data.activeId}`]) {
      this.setData({
        loadHidden: true
      })
      this.reqData2();
    }
  },
  onPullDownRefresh:function(){
    this.setData({
      pullRefresh:true
    })
    this.reqData1();
  },
  /***
   * 关闭红包弹窗
  */
  closeRed:function(){
    // console.time('closeRed');
    this.setData({
      redHidden:true
    })
    // console.timeEnd('closeRed');
  },
  /***
   * 领取红包
  */
  getNewMoney(e){
    var that=this;
    if(!app.isLogin()){
      that.getUserInfo(e,1);
    }else if(that.data.user.newp==1){
      wx.showToast({
        title: '您已领过此红包！',
        icon:'none'
      })
      that.setData({
        redHidden: true
      })
    }else{
      app.func.postReq('/text/index.php/home/user/lqnew',{newprice:that.data.newprice},function(res){
        if(res==1){
          that.setData({
            redHidden: true
          })
          wx.showToast({
            title: '领取成功',
            icon:'none'
          })
        }
      });
    }
  },
  getUserInfo1(e){
    var that = this;
    var data = {};
    if (e.detail.errMsg == "getUserInfo:ok") {
      that.login(e.detail.userInfo, e,1);
    }
  },
  onShareAppMessage:function(){

  }
})
